<template>
  <el-button plain type="primary" @click="handleAddGroup">
    新增模板文件
  </el-button>
  <el-button plain type="primary" @click="back2top">
    返回模板列表
  </el-button>
  <el-table :data="tableData" style="width: 100%">
    <el-table-column prop="templateFileName" label="文件名" width="300"/>
    <el-table-column prop="fileDirPath" label="文件目录层级" width="300"/>
    <el-table-column prop="fileDesc" label="文件描述" width="300"/>
    <el-table-column fixed="right" label="Operations" min-width="300">
      <template #default="scope">
        <el-button link type="primary" @click="handleUpdateFileGroup(scope)">
          在线编辑模板内容
        </el-button>
        <el-button link type="primary" @click="handleUpdateGroup(scope)">
          修改基础信息
        </el-button>
        <el-popconfirm title="是否确认删除?" @confirm="handleDeleteGroup(scope)">
          <template #reference>
            <el-button link type="primary">
              删除
            </el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>

  <el-dialog v-model="dialogFormVisible" :title="formTitle" width="500">
    <el-form :model="form">
      <el-form-item label="模板文件名" :label-width="formLabelWidth">
        <el-input v-model="form.templateFileName" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="模板文件描述" :label-width="formLabelWidth">
        <el-input v-model="form.fileDesc" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="模板文件的目录层级" :label-width="formLabelWidth">
        <el-input v-model="form.fileDirPath" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="文件名称生成模板" :label-width="formLabelWidth">
        <el-input v-model="form.generateFileName" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="模板文件文本内容" :label-width="formLabelWidth">
        <el-input
          v-model="form.templateFileContent"
          style="width: 240px"
          :rows="3"
          type="textarea"
          placeholder="如果上传模板文件可以不填"
        />
      </el-form-item>
      <el-form-item label="模板文件文本内容" :label-width="formLabelWidth">
        <el-upload
          ref="upload"
          v-model:file-list="uploadFileList"
          class="upload-demo"
          action=""
          :auto-upload="false"
          :on-change="handleChange"
          :on-exceed="handleExceed"
          :limit="1"
        >
          <template #trigger>
            <el-button type="primary">选择模板文件</el-button>
          </template>
          <template #tip>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="saveGroupChange">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {instance} from '@/api/base'
import {onMounted, reactive, ref} from 'vue'

import type {UploadInstance, UploadProps, UploadRawFile, UploadUserFile} from 'element-plus'
import {genFileId} from 'element-plus'
import {useRoute, useRouter} from 'vue-router'

const route = useRoute()
const router = useRouter()

const groupData = ref({})
const isUpload = ref(false)

const upload = ref<UploadInstance>()
const uploadFileList = ref<UploadUserFile[]>([])
const handleChange: UploadProps['onChange'] = (uploadFile, uploadFiles) => {
  isUpload.value = true
  // uploadFile 选择的文件 只能选一个
  console.log('上传1', uploadFile)
  console.log('上传2', uploadFiles)
  uploadFileList.value = [uploadFile]
  console.log(uploadFileList.value.length, uploadFileList.value)
}
const handleExceed: UploadProps['onExceed'] = (files) => {
  isUpload.value = true
  console.log('onExceed', files)
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
  console.log('onExceed2', uploadFileList.value)
}

const tableData = ref([])
const dialogFormVisible = ref(false)
const formLabelWidth = ref('140px')
const formTitle = ref('')
const form = reactive({
  pkid: '',
  groupId: '',
  templateFileName: '',
  fileDesc: '',
  fileDirPath: '',
  generateFileName: '',
  templateFileContent: '',
})
const handleAddGroup = () => {
  form.pkid = ''
  form.groupId = ''
  form.templateFileName = ''
  form.fileDesc = ''
  form.fileDirPath = ''
  form.generateFileName = ''
  form.templateFileContent = ''
  formTitle.value = '新增'
  if (upload.value) {
    upload.value!.clearFiles()
  }
  uploadFileList.value = []
  dialogFormVisible.value = true
}

const handleUpdateGroup = (scope) => {
  const selectItem = tableData.value[scope.$index]
  form.pkid = selectItem.pkid
  form.groupId = selectItem.groupId
  form.templateFileName = selectItem.templateFileName
  form.fileDesc = selectItem.fileDesc
  form.fileDirPath = selectItem.fileDirPath
  form.generateFileName = selectItem.generateFileName
  form.templateFileContent = selectItem.templateFileContent
  uploadFileList.value = [
    {
      name: selectItem.templateFileName,
      url: selectItem.fileUrl,
    },
  ]
  formTitle.value = '编辑'
  dialogFormVisible.value = true
}

const saveGroupChange = () => {
  saveTemplateGroup()
}

const handleDeleteGroup = (scope) => {
  deleteTemplateGroup(tableData.value[scope.$index].pkid)
}

const deleteTemplateGroup = (id) => {
  instance.post('/templateFileInfo/deleteTemplate?id=' + id).then((res) => {
    console.log(res)
    listFileByGroupId()
  }).catch((err) => {
    console.log(err)
  })
}

const handleUpdateFileGroup = (scope) => {
  router.push({
    name: 'fileEditor',
    query: {
      groupId: groupData.value
    }
  })
}

const saveTemplateGroup = () => {
  instance.post('/templateFileInfo/saveTemplate', {
    pkid: form.pkid,
    groupId: groupData.value,
    templateFileName: form.templateFileName,
    fileDesc: form.fileDesc,
    fileDirPath: form.fileDirPath,
    generateFileName: form.generateFileName,
    templateFileContent: form.templateFileContent,
    uploadTemplateFile: uploadFileList.value.length == 0 || !isUpload ? undefined : uploadFileList.value[0].raw,
  }, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then((res) => {
    console.log(res)
    listFileByGroupId()
    dialogFormVisible.value = false
  }).catch((err) => {
    console.log(err)
  })
}

const listFileByGroupId = () => {
  instance.post('/templateFileInfo/listFileByGroupId', {
    groupId: groupData.value,
  }).then((res) => {
    tableData.value = [...res.data.data]
  }).catch((err) => {
    console.log(err)
  })
}

const back2top = () => {
  router.push({name: 'modelList'})
}

onMounted(() => {
  console.log(route)
  console.log(route.query.groupId)
  groupData.value = route.query.groupId
  if (!groupData.value) {
    router.push({name: 'modelList'})
  }
  console.log(groupData)
  listFileByGroupId()
})

</script>

<style scoped>


</style>
